<template>
  <el-drawer :title="!dataForm.id ? '新增' : '修改'" :visible.sync="visible" :modal="false" :with-header="false" size="calc(100% - 230px)">
    <div>
      <!--      上传媒体弹框-->
      <el-drawer size="650px" :with-header="false" :append-to-body="true" :visible.sync="innerDrawer">
        <div class="right-container">
          <div class="container-header">
            <div style="font-size: 14px">课程资源</div>
            <div @click="handleInnerClose">
              <i class="el-icon-close" style="font-size: 18px"></i>
            </div>
          </div>
          <div class="container-content background-color-grey padding-10">
            <div class="background-color-white padding-10">
              <el-form :model="addCourse" :rules="addCourseRule" ref="addCourse" label-width="80px">
                <el-form-item label="资源名称" prop="name">
                  <el-input v-model="addCourse.name" style="width: 360px" placeholder="资源名称"></el-input>
                </el-form-item>
                <el-form-item label="资源上传" prop="url">
                  <OssUploadVideo :limit="1" :fileType="fileType" :fileSize="5120" :isShowUploadVideo="true"
                    ref="videoUploadRef" @input="uploadVideo" :isShowBtn="true"></OssUploadVideo>
                </el-form-item>
                <el-form-item label="资源地址" prop="url">
                  <el-input v-model="addCourse.url" placeholder="资源地址" @blur="showVideo()"></el-input>
                </el-form-item>
                <el-form-item label="是否必学" prop="requireCompleted">
                  <el-radio-group v-model="addCourse.requireCompleted" aria-label="是否必学选项">
                    <el-radio :label="0" aria-label="是">是</el-radio>
                    <el-radio :label="1" aria-label="否">否</el-radio>
                  </el-radio-group>
                </el-form-item>
                <!--                完整播放-->
                <el-form-item label="完整播放" prop="payAll">
                  <el-radio-group v-model="addCourse.payAll" aria-label="完整播放选项">
                    <el-radio :label="1">需要</el-radio>
                    <el-radio :label="0">不需要</el-radio>
                  </el-radio-group>
                </el-form-item>
                <!--                进度跳转-->
                <el-form-item label="进度跳转" prop="payJump">
                  <el-radio-group v-model="addCourse.payJump" aria-label="进度跳转选项">
                    <el-radio :label="0">允许</el-radio>
                    <el-radio :label="1">不允许</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                  <div class="flex">
                    <el-input style="width: 100px" v-model="addCourse.sort" placeholder="排序"></el-input>
                    <div class="margin-left-sm text-gray">数字越大，排列靠前</div>
                  </div>
                </el-form-item>
              </el-form>

            </div>
          </div>
          <div class="flex justify-center padding-10">
            <el-button type="primary" @click="addCourseSubmit('video')">保存</el-button>
          </div>
        </div>
      </el-drawer>

      <!-- 上传文档弹窗 -->
      <el-drawer size="650px" :with-header="false" :append-to-body="true" :visible.sync="documentDrawer">
        <div class="right-container">
          <div class="container-header">
            <div style="font-size: 14px">课程资源</div>
            <div @click="handleDocumentClose">
              <i class="el-icon-close" style="font-size: 18px"></i>
            </div>
          </div>
          <div class="container-content background-color-grey padding-10">
            <div class="background-color-white padding-10">
              <el-form :model="addCourse" :rules="addCourseRule" ref="addCourseDocument" label-width="80px">
                <el-form-item label="资源名称" prop="name">
                  <el-input v-model="addCourse.name" style="width: 360px" placeholder="资源名称"></el-input>
                </el-form-item>
                <el-form-item label="资源上传" prop="url">
                  <OssUploadIFileButton :limit="1" :fileType="documentFileType" :fileSize="50" :isShowUploadVideo="true"
                    ref="fileUploadRef" @input="uploadFile" :isShowBtn="true"></OssUploadIFileButton>
                </el-form-item>
                <el-form-item label="资源地址" prop="url" v-if="addCourse.url">
                  <el-input v-model="addCourse.url" placeholder="资源地址" disabled></el-input>
                </el-form-item>
                <el-form-item label="是否必学" prop="requireCompleted">
                  <el-radio-group v-model="addCourse.requireCompleted" aria-label="是否必学选项">
                    <el-radio :label="0" aria-label="是">是</el-radio>
                    <el-radio :label="1" aria-label="否">否</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="学习时长" prop="sort">
                  <div class="flex">
                    <el-input style="width: 100px" v-model="addCourse.learningTime" placeholder="秒"></el-input>
                    <div class="margin-left-sm text-gray">需要学习够指定时间视为通过</div>
                  </div>
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                  <div class="flex">
                    <el-input style="width: 100px" v-model="addCourse.sort" placeholder="排序"></el-input>
                    <div class="margin-left-sm text-gray">数字越大，排列靠前</div>
                  </div>
                </el-form-item>
              </el-form>

            </div>
          </div>
          <div class="flex justify-center padding-10">
            <el-button type="primary" @click="addCourseSubmit('pdf')">保存</el-button>
          </div>
        </div>
      </el-drawer>
      <!--      添加考试弹窗-->
      <el-drawer size="650px" :with-header="false" :append-to-body="true" :visible.sync="addExamDrawer">
        <div class="right-container">
          <div class="container-header">
            <div style="font-size: 14px">考试设置</div>
            <div @click="handleAddExamClose">
              <i class="el-icon-close" style="font-size: 18px"></i>
            </div>
          </div>
          <div class="container-content background-color-grey padding-10">
            <div class="background-color-white padding-10">
              <el-form :model="addExam" :rules="addExamRule" ref="addExam" label-width="80px">
                <el-form-item label="考试名称" prop="name">
                  <el-input v-model="addExam.name" placeholder="考试名称"></el-input>
                </el-form-item>
                <el-form-item label="总分" prop="totalScore">
                  <el-input v-model="addExam.totalScore" placeholder="总分"></el-input>
                </el-form-item>
                <el-form-item label="合格分" prop="passScore">
                  <el-input disabled v-model="addExam.passScore" placeholder="合格分"></el-input>
                </el-form-item>
                <!-- <el-form-item label="出题模式" prop="isRandom">
                  <el-radio-group v-model="addExam.isRandom">
                    <el-radio :label="0">手动</el-radio>
                    <el-radio :label="1">导入</el-radio>
                  </el-radio-group>
                </el-form-item> -->
                <!-- 如果是手动出题，显示添加试题按钮，如果是导入，显示上传课件和下载模板按钮 -->
                <el-form-item label="试题设置" prop="examItemList" v-if="addExam.isRandom === 0">
                  <div>
                    <el-button type="primary" size="mini" @click="addExamItemOpen()">添加试题</el-button>
                    <span class="margin-left-sm cursor-pointer text-primary">试题数量({{ addExam.examItemList.length
                      }})</span>
                  </div>
                  <template v-if="addExam.examItemList && addExam.examItemList.length > 0">
                    <el-card v-for="(item, index) in addExam.examItemList" class="box-card addExamCard margin-top-sm"
                      :key="item.name">
                      <div>
                        <div style="min-height: 40px;line-height: 30px"
                          class="flex justify-between align-center border-bottom padding-lr-sm">
                          <div class="flex-1 text-16">{{ index + 1 }}、{{ item.name }}</div>
                          <div>
                            <el-button type="text" size="mini" v-if="index !== 0"
                              @click="handleAddExamItemUp(index)">上移</el-button>
                            <el-button type="text" size="mini" v-if="index !== addExam.examItemList.length - 1"
                              @click="handleAddExamItemDown(index)">下移</el-button>
                            <el-button type="text" size="mini" @click="handleAddExamItemDelete(index)">删除</el-button>
                          </div>

                        </div>
                        <div class="flex-column justify-between padding-lr-lg">
                          <div v-if="item.a" class="padding-lr-lg margin-tb-sm" :class="item.ans.indexOf('a')!=-1 ? 'bg-green text-white' : ''">
                            A.&nbsp;{{ item.a }}
                          </div>
                          <div v-if="item.b" class="padding-lr-lg margin-tb-sm" :class="item.ans.indexOf('b')!=-1 ? 'bg-green text-white' : ''">
                            B.&nbsp;{{ item.b }}
                          </div>
                          <div v-if="item.c" class="padding-lr-lg margin-tb-sm" :class="item.ans.indexOf('c')!=-1 ? 'bg-green text-white' : ''">
                            C.&nbsp;{{ item.c }}
                          </div>
                          <div v-if="item.d" class="padding-lr-lg margin-tb-sm" :class="item.ans.indexOf('d')!=-1 ? 'bg-green text-white' : ''">
                            D.&nbsp;{{ item.d }}
                          </div>
                        </div>

                      </div>
                    </el-card>
                  </template>

                </el-form-item>


              </el-form>

            </div>
          </div>
          <div class="flex justify-center padding-10">
            <el-button type="primary" @click="addExamSubmit">保存</el-button>
          </div>
        </div>

      </el-drawer>
      <!--      添加考试试题弹窗-->
      <el-drawer size="650px" :with-header="false" :append-to-body="true" :visible.sync="addExamItemDrawer">
        <div class="right-container">
          <div class="container-header">
            <div style="font-size: 14px">添加试题</div>
            <div @click="handleAddExamItemClose">
              <i class="el-icon-close" style="font-size: 18px"></i>
            </div>
          </div>
          <div class="container-content background-color-grey padding-10">
            <div class="background-color-white padding-10">
              <el-form :model="addExamItem" :rules="addExamItemRule" ref="addExamItem" label-width="80px">

                <el-form-item label="题目" prop="name">
                  <el-input v-model="addExamItem.name" type="textarea" placeholder="请输入题目"></el-input>
                </el-form-item>
                <el-form-item label="选项" prop="option">
                  <!-- 选项 A，B，C，D，后边有个输入框，输入框的值是选项的内容，再后边有个单选框，单选框的值是是否正确答案 -->
                  <div class="flex-cloumn">
                    <div class="flex justify-between align-center margin-top-sm">
                      <span>A、</span>
                      <el-input class="flex-1" v-model="addExamItem.a" placeholder="请输入内容"></el-input>
                      <!-- 使用div画一个单选框，选中里边打一个对号 -->
                      <div class=" margin-lr-sm cursor-pointer" @click="changeAns('a')">
                        <div class="radio-check" v-if="addExamItem.ans.indexOf('a')!=-1">√</div>
                        <div class="radio-no-check" v-else></div>
                      </div>

                    </div>
                    <div class="flex justify-between align-center margin-top-sm">
                      <span>B、</span>
                      <el-input class="flex-1" v-model="addExamItem.b" placeholder="请输入内容"></el-input>
                      <div class=" margin-lr-sm cursor-pointer" @click="changeAns('b')">
                        <div class="radio-check" v-if="addExamItem.ans.indexOf('b')!=-1">√</div>
                        <div class="radio-no-check" v-else></div>
                      </div>
                    </div>
                    <div class="flex justify-between align-center margin-top-sm">
                      <span>C、</span>
                      <el-input class="flex-1" v-model="addExamItem.c" placeholder="请输入内容"></el-input>
                      <div class=" margin-lr-sm cursor-pointer" @click="changeAns('c')">
                        <div class="radio-check" v-if="addExamItem.ans.indexOf('c')!=-1">√</div>
                        <div class="radio-no-check" v-else></div>
                      </div>
                    </div>
                    <div class="flex justify-between align-center margin-top-sm">
                      <span>D、</span>
                      <el-input class="flex-1" v-model="addExamItem.d" placeholder="请输入内容"></el-input>
                      <div class=" margin-lr-sm cursor-pointer" @click="changeAns('d')">
                        <div class="radio-check" v-if="addExamItem.ans.indexOf('d')!=-1">√</div>
                        <div class="radio-no-check" v-else></div>
                      </div>
                    </div>

                  </div>

                </el-form-item>
                <el-form-item label="排序" prop="sort">
                  <div class="flex">
                    <el-input style="width: 100px" v-model="addExamItem.sort" placeholder="排序"></el-input>
                    <div class="margin-left-sm text-gray">数字越大，排列靠前</div>
                  </div>
                </el-form-item>
              </el-form>

            </div>
          </div>
          <div class="flex justify-center padding-10">
            <el-button type="primary" @click="addExamItemSubmit">保存</el-button>
          </div>
        </div>
      </el-drawer>



    </div>

    <div class="right-container">
      <div class="container-header">
        <div style="font-size: 14px">新增修改</div>
        <div @click="handleClose">
          <i class="el-icon-close" style="font-size: 18px"></i>
        </div>
      </div>
      <div class="container-content background-color-grey padding-10" style="overflow: auto">
        <div class="background-color-white ">
          <div class="flex justify-between align-center margin-bottom-sm padding-lg border-bottom card-heard-title">
            <div>
              <i class="el-icon-collection-tag" style="font-size: 18px"></i>
              基础信息
            </div>
          </div>
          <div class="padding-lr-lg padding-tb-md">
            <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="80px">
              <el-form-item label="标题名称" prop="name">
                <el-input v-model="dataForm.name" placeholder="标题名称"></el-input>
              </el-form-item>
              <el-form-item label="业务编号" prop="code">
                <div class="flex">
                  <el-input style="width: 100px" v-model="dataForm.code" placeholder="业务编号"></el-input>
                  <div class="margin-left-sm text-gray">业务编号，不填则自动生成</div>
                </div>
              </el-form-item>
              <el-form-item label="学年学期" prop="studyId">
                <el-select v-model="dataForm.studyId" placeholder="学年学期" @change="changeStudy()" >
                  <el-option v-for="item in studyOptions" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="课程学时" prop="credit">
                <el-input type="number" v-model="dataForm.credit" placeholder="" @blur="calPrice"></el-input>

              </el-form-item>
              <el-form-item label="讲师姓名" prop="attributeName">
                <el-input v-model="dataForm.attributeName" placeholder=""></el-input>

              </el-form-item>
              <el-form-item label="讲师职称" prop="attributeTitle">
                <el-input v-model="dataForm.attributeTitle" placeholder=""></el-input>

              </el-form-item>
              <el-form-item label="讲师单位" prop="attributeUnit">
                <el-input v-model="dataForm.attributeUnit" placeholder=""></el-input>
              </el-form-item>
              <el-form-item label="讲师简介" prop="attributeDescs">
                <el-input v-model="dataForm.attributeDescs" placeholder=""></el-input>
              </el-form-item>
            </el-form>
          </div>

          <div class="div-jiange"></div>
          <div class="flex justify-between align-center margin-bottom-sm padding-lg border-bottom card-heard-title">
            <div>
              <i class="el-icon-collection-tag" style="font-size: 18px"></i>
              封面图
            </div>
          </div>
          <div class="padding-lr-lg padding-tb-md">
            <el-form :model="dataForm" :rules="dataRule" ref="dataFormUpload" label-width="80px">
              <el-form-item label="生成方式" size="mini" prop="status">
                <el-radio-group v-model="dataFormUpload.status">
                  <el-radio :label="0">上传图片</el-radio>
                  <el-radio :label="1">自动生成</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="上传图片" size="mini" prop="thumbnail"
                v-if="dataFormUpload.status == 0 || (dataFormUpload.status == 1 && dataForm.thumbnail)">
                <OssUploadImg :limit="1" :fileType="['image/*']" :fileSize="5120" :isShowUploadImg="true"
                  ref="imgUploadRef" @input="uploadImg" :isShowBtn="true"></OssUploadImg>
              </el-form-item>
              <!-- <el-form-item label="上传图片" size="mini" prop="thumbnail" v-if="dataFormUpload.status==1&&dataForm.thumbnail">
                <OssUploadImg :limit="1" :fileType="['image/*']" :fileSize="5120" :isShowUploadImg="true"
                  ref="imgUploadRef" @input="uploadImg" :isShowBtn="true"></OssUploadImg>
              </el-form-item> -->
              <el-form-item label="上传图片" size="mini" prop="thumbnail"
                v-if="dataFormUpload.status == 1 && !dataForm.thumbnail">
                <el-button type="primary" @click="generatorImg">点此生成</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div class="div-jiange"></div>

          <div>
            <div class="flex justify-between align-center margin-bottom-sm padding-lg border-bottom card-heard-title">
              <div>
                <i class="el-icon-collection-tag" style="font-size: 18px"></i>
                课程资源
              </div>

              <div>
                <el-button type="primary" size="mini" @click="addCourseDocumentOpen()">添加文档</el-button>

                <el-button type="primary" size="mini" @click="addCourseOpen()">添加媒体</el-button>
              </div>
            </div>
            <div class="padding-lr-lg padding-tb-md">
              <el-table ref="manageItemListRef" :header-cell-style="tableHeaderStyle" :data="dataForm.manageItemList"
                border v-loading="dataListLoading" style="width: 100%;">
                <el-table-column header-align="center" align="center" width="130" label="预览">
                  <template slot-scope="scope">
                    <img :src="dataForm.thumbnail" style="width:100px;height:60px;" mode="aspectFill" />
                  </template>
                </el-table-column>

                <el-table-column prop="name" header-align="left" align="left" label="名称">
                </el-table-column>

                <el-table-column prop="requireCompleted" header-align="center" align="center" width="100" label="是否必学">
                  <template slot-scope="scope">
                    <span v-if="scope.row.requireCompleted === 0" size="small" type="danger">是</span>
                    <span v-else size="small">否</span>
                  </template>
                </el-table-column>

                <el-table-column prop="payAll" header-align="center" align="center" width="100" label="完整播放	">
                  <template slot-scope="scope">
                    <span v-if="scope.row.payAll === 0">不需要</span>
                    <span v-else size="small">需要</span>
                  </template>
                </el-table-column>

                <el-table-column prop="payJump" header-align="center" align="center" width="100" label="进度跳转	">
                  <template slot-scope="scope">
                    <span v-if="scope.row.payJump === 0" size="small" type="danger">允许</span>
                    <span v-else size="small">不允许</span>
                  </template>
                </el-table-column>

                <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
                  <template slot-scope="scope">

                    <el-button type="text" size="small" v-if="scope.row.fileType == 'pdf'"
                      @click="addCourseDocumentOpen(scope.row, scope.$index)">修改</el-button>
                    <el-button type="text" size="small" v-else
                      @click="addCourseOpen(scope.row, scope.$index)">修改</el-button>

                    <el-button type="text" size="small" @click="deleteAddCourse(scope.row, scope.$index)">删除</el-button>

                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
          <div class="div-jiange"></div>
          <div>
            <div class="flex justify-between align-center margin-bottom-sm padding-lg border-bottom card-heard-title">
              <div>
                <i class="el-icon-collection-tag" style="font-size: 18px"></i>
                课程考核
              </div>
              <div>
                <el-button type="primary" size="mini" @click="addExamOpen()">添加</el-button>
              </div>
            </div>
            <div class="padding-lr-lg padding-tb-md">
              <el-table ref="examListRef" :header-cell-style="tableHeaderStyle" :data="dataForm.examList" border
                v-loading="dataListLoading" style="width: 100%;">
                <el-table-column prop="name" header-align="left" align="left" label="考试名称">
                </el-table-column>
                <!-- 操作 修改 删除 -->
                <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
                  <template slot-scope="scope">
                    <el-button type="text" size="small" @click="addExamOpen(scope.row, scope.$index)">修改</el-button>
                    <el-button type="text" size="small" @click="deleteAddExam(scope.row, scope.$index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>

          <div class="div-jiange"></div>
          <div>
            <div class="flex justify-between align-center margin-bottom-sm padding-lg border-bottom card-heard-title">
              <div>
                <i class="el-icon-collection-tag" style="font-size: 18px"></i>
                产品价格
              </div>
            </div>
            <div class="padding-lr-lg padding-tb-md">
              <el-form :model="dataForm" :rules="dataRule" ref="dataFormPrice" label-width="80px">
                <el-form-item label="单价" prop="price">
                  <div class="flex">
                    <el-input style="width: 300px" v-model="dataForm.price" placeholder="单价"></el-input>
                    <div class="margin-left-sm text-gray">元</div>
                  </div>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
      </div>
      <div class="flex justify-center padding-10">
        <el-button type="primary" @click="dataFormSubmit">保存</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import OssUploadVideo from '../oss/oss-upload-video.vue';
import OssUploadImg from '../oss/oss-upload-img.vue';
import OssUploadIFileButton from '../oss/oss-upload-file-button.vue';

export default {
  components: {
    OssUploadVideo,
    OssUploadImg,
    OssUploadIFileButton
  },
  data() {
    return {
      configForm: {},
      height: 240,
      dataListLoading: false,
      dataListSelections: [],
      tableHeaderStyle: { background: '#f5f7fa !important', height: '20px !important', padding: '4px !important' },
      direction: 'rtl',
      innerDrawer: false,
      documentDrawer: false,
      selectExamDrawer: false,
      addExamDrawer: false,
      addExamItemDrawer: false,
      visible: false,
      addCourse: {
        manageId: '',
        manageName: '',
        name: '',
        content: '',
        thumbnail: '',
        url: '',
        requireCompleted: 1,
        payAll: 1,
        payJump: 1,
        sort: 1,
      },
      selectCourseIndex: -1,
      addExam: {
        manageId: '',
        manageName: '',
        name: '',
        isRandom: 0,
        totalNum: '',
        totalScore: 100,
        passScore: 60,
        sort: 1,
        examItemList: [],
      },
      selectIndexExam: -1,
      addExamItem: {
        name: '',
        a: '',
        b: '',
        c: '',
        d: '',
        ans: '',
        examId: "",
        sort: 1,
      },
      dataForm: {
        id: 0,
        name: '',
        code: '',
        studyId: '',
        type: '',
        credit: '',
        attributeName: '',
        attributeTitle: '',
        attributeUnit: '',
        attributeDescs: '',
        thumbnail: '',
        price: 0,
        status: 0,
        sort: 1,
        manageItemList: [],
        examList: [],
      },
      dataFormOther: {
        type: [],
      },
      dataFormUpload: {
        status: 0
      },
      studyOptions: [
      ],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      formClass: {
        ossUrl: "https://image.cnslpa.com/", //阿里云oss地址-视频
      },
      fileType: ["video/*"],
      //只能上传pdf
      documentFileType: ["application/pdf"],
      dataRule: {
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ],
        studyId: [
          { required: true, message: '学年不能为空', trigger: 'blur' }
        ],
        thumbnail: [
          { required: true, message: '封面不能为空', trigger: 'blur' }
        ],
        credit: [
          { required: true, message: '学时不能为空', trigger: 'blur' }
        ],
      },
      addCourseRule: {
        name: [
          { required: true, message: '课程名称不能为空', trigger: 'blur' }
        ],
        url: [
          { required: true, message: '课程地址不能为空', trigger: 'blur' }
        ],
        requireCompleted: [
          { required: true, message: '是否必学不能为空', trigger: 'blur' }
        ],
        payAll: [
          { required: true, message: '完整播放不能为空', trigger: 'blur' }
        ],
        payJump: [
          { required: true, message: '进度跳转不能为空', trigger: 'blur' }
        ],
      },
      addExamRule: {
        name: [
          { required: true, message: '考试名称不能为空', trigger: 'blur' }
        ],
        totalScore: [
          { required: true, message: '总分不能为空', trigger: 'blur' }
        ],
        passScore: [
          { required: true, message: '合格分不能为空', trigger: 'blur' }
        ],
        examItemList: [
          { required: true, message: '请添加考试题目', trigger: 'blur' }
        ]
      },
      addExamItemRule: {
        name: [
          { required: true, message: '题目不能为空', trigger: 'blur' }
        ],
        a: [
          { required: true, message: '选项A不能为空', trigger: 'blur' }
        ],
        b: [
          { required: true, message: '选项B不能为空', trigger: 'blur' }
        ],
        c: [
          { required: true, message: '选项C不能为空', trigger: 'blur' }
        ],
        d: [
          { required: true, message: '选项D不能为空', trigger: 'blur' }
        ],
        ans: [
          { required: true, message: '答案不能为空', trigger: 'blur' }
        ],
      }
    }
  },
  watch: {
    "addExam.totalScore"(val) {
      if (val) {
        this.addExam.passScore = Number((val * (this.configForm.exam_pass_scroe_ratio ? (Number(this.configForm.exam_pass_scroe_ratio) / 100) : 0.6)).toFixed(2))
      }
    }
  },
  mounted() {
    console.log(document.body.clientHeight)
    // 至于减去多少，这个要看你的页面高度和你想将滚动轴固定在哪里了，数值可以更换
    // this.$nextTick(() => {
    //   let tableHeight = document.body.clientHeight - 275
    //   this.height = tableHeight
    // })
  },
  created() {
    this.getstudyOptionsList();
  },
  methods: {
    changeAns(ans){
      //ans用逗号分割
      let currentAns =  this.addExamItem.ans.split(",")
      //判断ans是否在currentAns中，如果在，移除，不在，添加
      if (currentAns.includes(ans)) {
        currentAns = currentAns.filter(item => item !== ans)
      } else {
        currentAns.push(ans)
      }
      let options = ["a","b","c","d"]
      //将currentAns按照options顺序排序，重新拼接字符串
      currentAns = options.filter(item => currentAns.includes(item)).join(",")
      this.addExamItem.ans = currentAns
      console.log(this.addExamItem.ans)
    },
    changeStudy(){
      if( this.dataForm.studyId){
        let studyId = this.dataForm.studyId.split("-");
        this.dataForm.type = studyId[1]
      }
      this.calPrice()
    },
    calPrice(){
      //如果是公需科目，不计算
      console.log(this.dataForm.type)
      if(this.dataForm.type==1||!this.dataForm.studyId){
        this.dataForm.price=0;
        return
      }
      if(this.dataForm.credit&&this.dataForm.credit>0){
        this.dataForm.price=Number(190/60*this.dataForm.credit).toFixed(2)
      }else{
        this.dataForm.price=0
      }

    },
    async generatorImg() {
      //生成之前验证 名称，讲师姓名，讲师职称，讲师单位必填
      if (!this.dataForm.name) {
        this.$message.error('标题名称不能为空')
        return
      }
      if (!this.dataForm.attributeName) {
        this.$message.error('讲师姓名不能为空')
        return
      }
      if (!this.dataForm.attributeTitle) {
        this.$message.error('讲师职称不能为空')
        return
      }
      if (!this.dataForm.attributeUnit) {
        this.$message.error('讲师单位不能为空')
        return
      }
      this.$loading({
        lock: true,
        text: "生成中",
        background: "rgba(0, 0, 0, 0.5)",
      });
      let res = await this.$http({
        url: this.$http.adornUrl(`/class/manage/getThumbnail`),
        method: 'post',
        data: this.$http.adornData({
          name: this.dataForm.name,
          attributeName: this.dataForm.attributeName,
          attributeTitle: this.dataForm.attributeTitle,
          attributeUnit: this.dataForm.attributeUnit,
        })
      })
      if (res.data && res.data.code === 0) {
        this.dataForm.thumbnail = res.data.url
        this.$message({
          message: '生成成功',
          type: 'success',
          duration: 1500,
          onClose: () => {
            this.$nextTick(() => {
              console.log(this.$refs['imgUploadRef']);
              this.initImgUrl(this.dataForm.thumbnail)
              this.$loading().close()

            });
          }
        })
      } else {
        this.$message({
          message: '生成失败',
          type: 'error',
          duration: 1500,
          onClose: () => {
          }
        })
        this.$loading().close()

      }

    },
    //获取全局配置
    async getConfig() {
      let res = await this.$http({
        url: this.$http.adornUrl(`/sys/ysxhConfig/list`),
        method: 'get',
        params: this.$http.adornParams()
      })

      let data = res.data
      if (data && data.code === 0) {
        console.log(data)
        this.configForm = Object.assign({}, this.dataForm, data.config.configMap)
      }
    },
    repairTable() {
      this.$nextTick(() => {
        // _self.$refs.你的el-table的ref.doLayout()
        this.$refs.manageItemListRef.doLayout();
        this.$refs.examListRef.doLayout();
      })
    },
    uploadVideo(data) {
      console.log("上传后的数据", data)
      this.addCourse.url = data.url
      this.addCourse.thumbnail = data.thumbnail
      this.addCourse.size = data.size
    },
    uploadImg(data) {
      console.log("上传后的数据", data)
      this.dataForm.thumbnail = data.url
    },
    uploadFile(data) {
      console.log("上传后的数据", data)
      this.addCourse.url = data.url
      this.addCourse.thumbnail = data.thumbnail
      this.addCourse.size = data.size
    },
    //获取学期学年数据
    getstudyOptionsList() {
      this.$http({
        url: this.$http.adornUrl('/class/study/list'),
        method: 'get',
        params: this.$http.adornParams({
          'page': 1,
          'limit': 9999999
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          if (data.page.list && data.page.list.length > 0) {
            for (let i = 0; i < data.page.list.length; i++) {
              this.studyOptions.push({
                value: data.page.list[i].id + "-0",
                label: data.page.list[i].name + "-专业科目"
              })
              this.studyOptions.push({
                value: data.page.list[i].id + "-1",
                label: data.page.list[i].name + "-公需科目"
              })
            }
          }
        }
      })
    },

    addCourseOpen(item, index) {
      //添加媒体之前判断必须上传封面
      if (!this.dataForm.thumbnail) {
        this.$message.error("请先上传封面");
        return;
      }
      console.log("添加修改课程对象，下标", item, index)
      if (item) {
        this.addCourse = item
        this.selectCourseIndex = index
      } else {
        this.initAddCourse();
      }
      this.addCourse.fileType = "video"
      this.$nextTick(() => {
        console.log(this.$refs['videoUploadRef']); // 确认引用是否存在
        if (this.$refs['videoUploadRef'] && typeof this.$refs['videoUploadRef'].initVideoUrl === 'function') {
          console.log('initVideoUrl 方法存在，执行 initVideoUrl 方法', this.addCourse.url);
          this.$refs['videoUploadRef'].initVideoUrl(this.addCourse.url, this.addCourse.thumbnail);
        } else {
          console.error('initVideoUrl 方法不存在或 videoUploadRef 引用未正确设置');
        }
      });

      this.innerDrawer = true;
      this.repairTable()
    },

    showVideo(){
     if (this.$refs['videoUploadRef'] && typeof this.$refs['videoUploadRef'].initVideoUrl === 'function') {
          console.log('initVideoUrl 方法存在，执行 initVideoUrl 方法', this.addCourse.url);
          this.$refs['videoUploadRef'].initVideoUrl(this.addCourse.url, this.addCourse.thumbnail);
        } else {
          console.error('initVideoUrl 方法不存在或 videoUploadRef 引用未正确设置');
        }
    },
    addCourseDocumentOpen(item, index) {
      //添加媒体之前判断必须上传封面
      if (!this.dataForm.thumbnail) {
        this.$message.error("请先上传封面");
        return;
      }
      console.log("添加修改课程对象，下标", item, index)
      if (item) {
        this.addCourse = item
        this.selectCourseIndex = index
      } else {
        this.initAddCourse();
      }
      this.addCourse.fileType = "pdf"
      this.documentDrawer = true;
      this.$nextTick(() => {
        console.log(this.$refs['fileUploadRef']); // 确认引用是否存在
        if (this.$refs['fileUploadRef'] && typeof this.$refs['fileUploadRef'].initImgUrl === 'function') {
          console.log('initImgUrl 方法存在，执行 initImgUrl 方法', this.addCourse.url);
          this.$refs['fileUploadRef'].initImgUrl(this.addCourse.url, this.addCourse.thumbnail);
        } else {
          console.error('initImgUrl 方法不存在或 fileUploadRef 引用未正确设置');
        }
      });

      this.repairTable()
    },

    deleteAddCourse(item, index) {
      console.log(item)
      //弹窗确认删除吗？
      this.$confirm('确定删除该课程吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dataForm.manageItemList.splice(index, 1)
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      })


    },
    initAddCourse() {
      this.addCourse = {
        manageId: '',
        manageName: '',
        name: '',
        content: '',
        thumbnail: '',
        url: '',
        requireCompleted: 1,
        payAll: 1,
        payJump: 1,
        learningTime: 0,
        sort: (this.dataForm.manageItemList.length || 0) + 1,
      }
    },
    handleInnerClose() {
      this.innerDrawer = false;
      this.initAddCourse();
      this.selectCourseIndex = -1
    },
    handleDocumentClose() {
      this.documentDrawer = false;
      this.initAddCourse();
      this.selectCourseIndex = -1
    },
    async addCourseSubmit(type) {
      console.log(this.addCourse)
      //名称，url，排序必填
      if (!this.addCourse.name) {
        this.$message.error('名称不能为空')
        return
      }
      if (!this.addCourse.url) {
        this.$message.error('视频不能为空')
        return
      }
      // if (!this.addCourse.thumbnail) {
      //   this.$message.error('封面不能为空')
      //   return
      // }
      if (!this.addCourse.sort) {
        this.$message.error('排序不能为空')
        return
      }
      //上传资源
      let ossId = await this.addOssCourse({
        url: this.addCourse.url,
        thumbnail: this.dataForm.thumbnail,
        name: this.addCourse.name,
        size: this.addCourse.size,
        fileType: type
      })
      this.addCourse.ossId = ossId

      let addParams = Object.assign({}, this.addCourse)
      //判断下标是否是-1，如果是-1则是新增，否则是修改
      if (this.selectCourseIndex == -1) {
        this.dataForm.manageItemList.push(addParams)
      } else {
        this.dataForm.manageItemList[this.selectCourseIndex] = addParams
      }
      //this.dataForm.manageItemList根据sort排序
      this.dataForm.manageItemList.sort((a, b) => {
        return a.sort - b.sort
      })
      console.log(this.dataForm.manageItemList)
      this.handleInnerClose();
      this.handleDocumentClose();
    },

    async addOssCourse(params) {
      let res = await this.$http({
        url: this.$http.adornUrl('/sys/oss/save'),
        method: 'post',
        data: this.$http.adornData(params)
      })
      console.log(res)
      return res.data.oss.id

    },


    handleClose() {
      this.visible = false; // 关闭外层 Drawer 时不关闭内层 Drawer
      this.handleAddExamClose();
      this.handleAddExamItemClose();
      this.handleInnerClose();
      this.handleDocumentClose();

    },

    addExamOpen(item, index) {
      console.log(item)
      console.log(index)
      if (item) {
        this.addExam = item
        this.selectIndexExam = index
      } else {
        this.initAddExam();
      }
      this.addExamDrawer = true
    },

       //删除
   async  deleteExam(id) {
      let res = await this.$http({
          url: this.$http.adornUrl('/class/exam/delete'),
          method: 'post',
          data: this.$http.adornData([id], false)
        })
    },

    deleteAddExam(item, index) {
      console.log(item)
      //弹窗确认删除吗？
      this.$confirm('确定删除该考试吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dataForm.examList.splice(index, 1)
        //判断是否有id，有id，删除数据
        if (item.id) {
          this.deleteExam(item.id)
        }else{
          this.$message({
          type: 'success',
          message: '删除成功!'
        });
        }
       
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      })

    },

    initAddExam() {
      this.addExam = {
        manageId: '',
        manageName: '',
        name: '',
        isRandom: 0,
        totalNum: '',
        totalScore: 100,
        passScore: 60,
        sort: (this.dataForm.examList.length || 0) + 1,
        examItemList: [],
      }
    },

    handleAddExamClose() {
      this.addExamDrawer = false;
      this.initAddExam();
      this.selectIndexExam = -1
    },

    addExamSubmit() {
      //名称，总分，合格分，排序必填，试题数量必须大于0
      if (!this.addExam.name) {
        this.$message.error('考试名称不能为空')
        return
      }
      if (!this.addExam.totalScore) {
        this.$message.error('总分不能为空')
        return
      }
      if (!this.addExam.passScore) {
        this.$message.error('合格分不能为空')
        return
      }
      if (!this.addExam.examItemList || this.addExam.examItemList.length <= 0) {
        this.$message.error('请添加考试题目')
        return
      }
      if (!this.addExam.sort) {
        this.$message.error('排序不能为空')
        return
      }
      let addParams = JSON.parse(JSON.stringify(this.addExam))
      //判断下标是否是-1，如果是-1则是新增，否则是修改
      if (this.selectIndexExam == -1) {
        this.dataForm.examList.push(addParams)
      } else {
        this.dataForm.examList[this.selectIndexExam] = addParams
      }
      this.handleAddExamClose();
    },

    addExamItemOpen() {
      this.initAddExamItem()
      this.addExamItemDrawer = true
    },

    initAddExamItem() {
      this.addExamItem = {
        name: '',
        a: '',
        b: '',
        c: '',
        d: '',
        ans: '',
        examId: "",
        sort: (this.addExam.examItemList.length || 0) + 1,
      }
    },

    handleAddExamItemDelete(index) {
      this.addExam.examItemList.splice(index, 1)
    },
    handleAddExamItemUp(index) {
      // 深拷贝当前的 examItemList 数组
      let tempList = JSON.parse(JSON.stringify(this.addExam.examItemList));

      // 确保 index - 1 不会越界
      if (index <= 0) return;

      // 获取当前项和前一项
      let current = tempList[index];
      let previous = tempList[index - 1];

      // 交换位置
      tempList[index] = previous;
      tempList[index - 1] = current;

      // 交换 sort 属性
      let tempSort = current.sort;
      current.sort = previous.sort;
      previous.sort = tempSort;

      // 更新到原数组
      this.addExam.examItemList = JSON.parse(JSON.stringify(tempList));

      console.log(this.addExam.examItemList);
    },

    handleAddExamItemDown(index) {
      // 深拷贝当前的 examItemList 数组
      let tempList = JSON.parse(JSON.stringify(this.addExam.examItemList));

      // 确保 index + 1 不会越界
      if (index >= tempList.length - 1) return;

      // 获取当前项和后一项
      let current = tempList[index];
      let next = tempList[index + 1];

      // 交换位置
      tempList[index] = next;
      tempList[index + 1] = current;

      // 交换 sort 属性
      let tempSort = current.sort;
      current.sort = next.sort;
      next.sort = tempSort;

      // 更新到原数组
      this.addExam.examItemList = JSON.parse(JSON.stringify(tempList));

      console.log(this.addExam.examItemList);
    },

    handleAddExamItemClose() {
      this.addExamItemDrawer = false;
      this.initAddExamItem();
    },

    addExamItemSubmit() {
      console.log(this.addExamItem)
      //名称，选项，答案，排序必填
      if (!this.addExamItem.name) {
        this.$message.error('题目不能为空')
        return
      }
      //判断每个选项是否填写
      // if (!this.addExamItem.a || !this.addExamItem.b || !this.addExamItem.c || !this.addExamItem.d) {
      //   this.$message.error('选项不能为空')
      //   return
      // }
      //判断答案是否填写
      if (!this.addExamItem.ans) {
        this.$message.error('答案不能为空')
        return
      }
      //验证答案对应的选项是否有值
      if (this.addExamItem.ans.indexOf('a')!=-1 && !this.addExamItem.a) {
        this.$message.error('选项A不能为空')
        return
      }
      if (this.addExamItem.ans.indexOf('b')!=-1 && !this.addExamItem.b) {
        this.$message.error('选项B不能为空')
        return
      }
      if (this.addExamItem.ans.indexOf('c')!=-1 && !this.addExamItem.c) {
        this.$message.error('选项C不能为空')
        return
      }
      if (this.addExamItem.ans.indexOf('d')!=-1 && !this.addExamItem.d) {
        this.$message.error('选项D不能为空')
        return
      }
      //判断排序是否填写
      if (!this.addExam.sort && this.addExam.sort !== 0) {
        this.$message.error('排序不能为空')
        return
      }
      console.log(this.addExamItem)
      this.addExam.examItemList.push(this.addExamItem)
      //this.addExam.examItemList根据sort排序
      this.addExam.examItemList.sort((a, b) => {
        return a.sort - b.sort
      })
      this.handleAddExamItemClose();
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },
    //渲染封面图
    initImgUrl(url) {
      if (this.$refs['imgUploadRef'] && typeof this.$refs['imgUploadRef'].initImgUrl === 'function') {
        console.log('initImgUrl 方法存在，执行 initImgUrl 方法', url);
        this.$refs['imgUploadRef'].initImgUrl(url)
      } else {
        console.error('initImgUrl 方法不存在或 initImgUrl 引用未正确设置');
      }
    },
    init(id) {
      this.dataForm.id = id || 0

      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
      })

      if (this.dataForm.id) {
        //loading
        this.$loading({
          lock: true,
          text: "加载中",
          background: "rgba(0, 0, 0, 0.5)",
        });
        this.$http({
          url: this.$http.adornUrl(`/class/manage/info/${this.dataForm.id}`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({ data }) => {
          if (data && data.code === 0) {
            console.log(data)
            this.dataForm = Object.assign({}, this.dataForm, data.classManage)
            //处理studyId
            this.dataForm.studyId = this.dataForm.studyId + "-" + this.dataForm.type
            //初始化封面
            this.$nextTick(() => {
              console.log(this.$refs['imgUploadRef']); // 确认引用是否存在
              this.initImgUrl(this.dataForm.thumbnail)
            });
          }
          this.$loading().close();
        }).catch((err) => {
          this.$loading().close();
        });
      } else {
        this.dataForm = {
          id: 0,
          name: '',
          code: '',
          studyId: '',
          type: '',
          credit: '',
          attributeName: '',
          attributeTitle: '',
          attributeUnit: '',
          attributeDescs: '',
          thumbnail: '',
          price: 0,
          status: 0,
          sort: 1,
          manageItemList: [],
          examList: [],
        }
        this.$nextTick(() => {
          console.log(this.$refs['imgUploadRef']);
          this.initImgUrl(this.dataForm.thumbnail)
        });
      }
      this.repairTable();
      this.getConfig();
    },
    // 表单提交
    dataFormSubmit() {
      let addParams = Object.assign({}, this.dataForm)
      //验证必填
      if (!addParams.name) {
        this.$message.error('名称不能为空')
        return
      }
      if (!addParams.studyId) {
        this.$message.error('学年学期不能为空')
        return
      }
      //封面必填
      if (!addParams.thumbnail) {
        this.$message.error('封面不能为空')
        return
      }
      //学时必填
      if (!addParams.credit) {
        this.$message.error('学时不能为空')
        return
      }
      //课程数量必须大于0
      if (!addParams.manageItemList || addParams.manageItemList.length <= 0) {
        this.$message.error('课程资源不能为空')
        return
      }

      //处理数据将studyId分割，取前面的值为studyId，后面的值为type
      if (addParams.studyId) {
        let studyId = addParams.studyId.split("-")
        addParams.studyId = studyId[0]
        addParams.type = studyId[1]
      }
      console.log(addParams)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/class/manage/${!this.dataForm.id ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData(addParams)
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    }
  }
}
</script>
<style>
.right-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.container-header {
  height: 50px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px
}

.container-content {
  flex: 1;
}


.flex-container {
  display: flex;
  justify-content: space-between;
  /* 根据需要调整 */
}

.flex-item {
  flex: 1;
  /* 可以根据需要调整比例 */
  margin: 0 10px;
  /* 添加一些间距 */
}

.left-panel,
.right-panel {
  /* 在这里添加任何特定的样式，比如背景色、边框等 */
}

.el-tabs--border-card>.el-tabs__content {
  padding: 10px 0;
}

.el-radio__original {
  display: none;
}

.addExamCard>.el-card__body {
  padding: 0px;
}
</style>
